// Use dynamic import for WASM
async function loadWasm() {
  try {
    console.log('Attempting to import kameo-wasm module...');
    
    // Dynamically import the WASM module
    const kameoModule = await import('kameo-wasm');
    console.log('kameo-wasm module imported, exports:', Object.keys(kameoModule).join(', '));
    
    // Make sure to initialize the WASM module first
    if (typeof kameoModule.default === 'function') {
      console.log('Initializing WASM module...');
      await kameoModule.default();
      console.log('WASM module initialized successfully');
    }
    
    // Define message types locally since they're not properly exported
    interface CounterInc { amount: number; }
    interface CounterGetCount {}
    
    if (!kameoModule.KameoWasm) {
      throw new Error('KameoWasm class not found in the imported module');
    }
    
    const { KameoWasm } = kameoModule;
    
    // Initialize the Kameo WASM API
    console.log('Creating new KameoWasm instance...');
    const kameo = new KameoWasm();
    console.log('Kameo WASM initialized');
    
    try {
      // Spawn a counter actor
      const counterActor = kameo.spawn('Counter', { count: 0 });
      console.log('Counter actor spawned');
      
      // Define a message conforming to the Counter.Inc interface
      const incMessage: CounterInc = { 
        amount: 5 
      };
      
      // Send the increment message and wait for reply
      const newCount = await counterActor.ask(incMessage);
      console.log(`Counter incremented. New count: ${newCount}`);
      
      // Get the current count
      const getCountMessage: CounterGetCount = {};
      const currentCount = await counterActor.ask(getCountMessage);
      console.log(`Current count: ${currentCount}`);
      
      // Register the actor so it can be looked up by name
      await kameo.register_actor(counterActor, 'my-counter');
      console.log('Actor registered with name: my-counter');
      
      // Look up the actor by name
      const lookedUpActor = await kameo.lookup_actor('Counter', 'my-counter');
      console.log('Actor lookup successful');
      
      // Increment using the looked up actor
      const newerCount = await lookedUpActor.ask({ amount: 10 });
      console.log(`Counter incremented via lookup. New count: ${newerCount}`);
      
    } catch (error) {
      console.error('Error in actor operations:', error);
    }
  } catch (error) {
    console.error('Failed to load WASM module:', error);
    // Log more details about the error
    if (error instanceof Error) {
      console.error('Error message:', error.message);
      console.error('Error stack:', error.stack);
    }
  }
}

// Add event listener for DOMContentLoaded to ensure the page is ready
document.addEventListener('DOMContentLoaded', () => {
  console.log('DOM loaded, initializing Kameo WASM example...');
  
  // Add a button to the UI to run the example
  const runButton = document.createElement('button');
  runButton.textContent = 'Run Counter Example';
  runButton.addEventListener('click', () => {
    console.log('Running example...');
    loadWasm().catch(error => {
      console.error('Unhandled error in loadWasm:', error);
    });
  });
  
  // Create a results div to show output
  const resultsDiv = document.createElement('div');
  resultsDiv.id = 'results';
  resultsDiv.style.marginTop = '20px';
  resultsDiv.style.padding = '10px';
  resultsDiv.style.border = '1px solid #ccc';
  resultsDiv.style.backgroundColor = '#f8f8f8';
  resultsDiv.textContent = 'Results will appear here...';
  
  // Add elements to the page
  document.body.appendChild(runButton);
  document.body.appendChild(resultsDiv);
  
  // Override console.log to also show in the results div
  const originalConsoleLog = console.log;
  console.log = function(...args) {
    originalConsoleLog.apply(console, args);
    const message = args.map(arg => 
      typeof arg === 'object' ? JSON.stringify(arg) : arg
    ).join(' ');
    
    const line = document.createElement('div');
    line.textContent = message;
    resultsDiv.appendChild(line);
  };
  
  const originalConsoleError = console.error;
  console.error = function(...args) {
    originalConsoleError.apply(console, args);
    const message = args.map(arg => 
      typeof arg === 'object' ? JSON.stringify(arg) : arg
    ).join(' ');
    
    const line = document.createElement('div');
    line.style.color = 'red';
    line.textContent = message;
    resultsDiv.appendChild(line);
  };
}); 